<template>
  <el-dialog
    width="85%"
    :title="$t('问题订单收货申请')"
    destroy-on-close
    append-to-body
    :visible.sync="show"
    :before-close="cancel"
  >
    <div class="apply-main" :style="type == 'edit' ? 'pointer-events: none;' : ''">
      <div class="apply-main-left">
        <el-form
          class="apply-main-left-search"
          @submit.native.prevent
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <!-- 订单号 -->
          <el-form-item prop="orderNo">
            <el-input :placeholder="$t('订单号')" v-model="queryParams.orderNo" clearable />
          </el-form-item>
          <el-form-item>
            <el-button
              v-hasPermi="['distribution:order:getOrderListByOrderNo']"
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList"
            >
              <!-- 搜索 -->
              {{ $t('搜索') }}
            </el-button>
          </el-form-item>
        </el-form>
        <div class="apply-main-left-title">{{ $t('订单列表') }}</div>
        <div class="apply-main-left_table">
          <el-table :height="calTableHeight() - 50" ref="mianRef" v-loading="loading" :data="tableData">
            <el-table-column show-overflow-tooltip width="180" :label="$t('订单号')" align="center" prop="orderNo" />
            <el-table-column show-overflow-tooltip :label="$t('店铺类型')" align="center" prop="shopType" />

            <el-table-column show-overflow-tooltip :label="$t('发货时间')" align="center" prop="deliverTime" />
            <el-table-column :label="$t('操作')" align="center">
              <template slot-scope="{ row }">
                <el-button
                  v-hasPermi="['distribution:order:getOrderApplyInfo']"
                  type="text"
                  @click="handleOrderNo(row)"
                >
                  {{ $t('选择') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="apply-main-right">
        <div class="apply-main-right-head">
          <el-row style="margin: 10px">
            <el-col :span="6"> {{ $t('订单号') }}:{{ orderDetail.orderNo }} </el-col>
            <el-col :span="3" :offset="1"> {{ $t('营业额') }}:{{ orderDetail.turnover }} </el-col>
            <el-col :span="3" :offset="1"> {{ $t('手续费') }}:{{ orderDetail.commission }} </el-col>
          </el-row>
          <el-row style="margin: 10px">
            <el-col :span="6"> {{ $t('包裹号') }}:{{ orderDetail.packageNo }} </el-col>
            <el-col :span="3" :offset="1"> {{ $t('运费') }}:{{ orderDetail.deliveryFee }} </el-col>
            <el-col :span="3" :offset="1"> {{ $t('捆包') }}:{{ orderDetail.bundleFee }} </el-col>
          </el-row>
          <el-row style="margin: 10px">
            <el-col :span="6"> {{ $t('店铺类型') }}:{{ orderDetail.shopType }} </el-col>
            <el-col :span="10" :offset="1"> {{ $t('店铺名') }}:{{ orderDetail.shopName }} </el-col>
          </el-row>
        </div>
        <div class="apply-main-right-list">
          <div class="apply-main-right-list_item">
            <div style="margin: 10px 0; font-weight: bold">{{ $t('订单sku') }}:</div>
            <el-table
              style="width: 100%"
              @selection-change="handleSelectionChange"
              :height="calTableHeight() - 350"
              :data="orderSkuTable"
            >
              <el-table-column type="selection" align="center" width="55" />

              <el-table-column show-overflow-tooltip align="center" prop="num">
                <template slot-scope="{ row }">
                  <div style="display: flex; align-items: center; justify-content: space-evenly">
                    {{ row.skuNo }}
                    <el-image
                      style="width: 20px; height: 20px; object-fit: cover"
                      :src="row.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
                    />
                    {{ row.handleNum }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('申请单价')" width="150" prop="applyPrice" align="center" />
            </el-table>
          </div>
          <div class="apply-main-right-list_item">
            <div class="apply-main-right-list_item_title">{{ $t('选择问题产品') }}:</div>
            <el-table style="width: 100%" ref="selectTableRef" :height="calTableHeight() - 350" :data="selectTable">
              <el-table-column show-overflow-tooltip align="center" prop="num">
                <template slot-scope="{ row }">
                  <div style="display: flex; align-items: center; justify-content: space-evenly">
                    {{ row.skuNo }}
                    <el-image
                      style="width: 20px; height: 20px; object-fit: cover"
                      :src="row.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
                    />
                    <el-input-number
                      size="mini"
                      v-model="row.handleNum"
                      controls-position="right"
                      :min="1"
                      :max="row.maxHandleNum"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('申请单价')" width="150" prop="applyPrice" align="center" />
            </el-table>
          </div>
        </div>
        <el-form
          size="small"
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="130px"
          label-position="top"
          style="display: flex; gap: 10px; padding: 10px; pointer-events: all"
        >
          <div style="flex: 1">
            <el-form-item :label="$t('申请原因')" prop="reason">
              <el-input type="textarea" :rows="8" v-model="form.reason" />
            </el-form-item>
            <el-form-item :label="$t('希望解决方式')" lt prop="wantProcessingMethod">
              <!-- 处理方式 1-换货 2-退款 3-补发 -->
              <el-select v-model="form.wantProcessingMethod" :disabled="type == 'edit'">
                <el-option label="换货" :value="1" />
                <el-option label="退款" :value="2" />
                <el-option label="补发" :value="3" />
              </el-select>
            </el-form-item>
          </div>

          <div style="flex: 3">
            <el-form-item :label="$t('贴图')" prop="imgList">
              <div style="border: 1px solid #ccc; overflow: auto; max-width: 600px; padding: 5px">
                <div class="template-img">
                  <ImgUploadManage
                    :uploadLimit="10"
                    type="6"
                    :businessId="form.id"
                    :limit="10"
                    :fileList.sync="form.imgList"
                  />
                </div>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        v-hasPermi="['distribution:orderQuestionApply:updateOrderQuestionApply']"
        @click="handleEditApply"
        v-show="type == 'edit'"
      >
        {{ $t('修改') }}
      </el-button>
      <el-button
        type="primary"
        @click="handleApply"
        v-show="type != 'edit'"
        v-hasPermi="['distribution:orderQuestionApply:insertOrderQuestionApply']"
      >
        {{ $t('申请') }}
      </el-button>
      <el-button @click="cancel">{{ $t('取消') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getOrderListByOrderNo,
  getOrderApplyInfo,
  insertOrderQuestionApply,
  updateOrderQuestionApply,
} from '@/api/orderManage/orderIssuesApplyList'
import { useDict } from '@/utils/useDict'

export default {
  // activated() {
  //   this.$nextTick(() => this.$refs['mianRef']?.doLayout())
  // },
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: {},
    },
    type: {
      type: String,
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      shop_type_list: [],
      tableCheck: [],
      orderSkuTable: [],
      selectTable: [],
      queryParams: {
        /**订单号 */
        orderNo: '',
      },
      loading: false,
      form: {
        imgList: '',
        reason: '',
        wantProcessingMethod: '',
      },
      orderDetail: {
        id: '',
        orderId: '',
        /**订单号*/
        orderNo: '',
        /**营业额 */
        turnover: '',
        /**手续费 */
        commission: '',
        /**包裹号 */
        packageNo: '',
        /**运费 */
        deliveryFee: '',
        /**捆包 */
        bundleFee: '',
        /**店铺类型 */
        shopType: '',
        /**店铺名 */
        shopName: '',
      },
      // 表单校验
      rules: {
        reason: [{ required: true, message: this.$t('请输入'), trigger: 'blur' }],
        wantProcessingMethod: [{ required: true, message: this.$t('请选择'), trigger: 'blur' }],
        imgList: [{ required: true, message: this.$t('请选择'), trigger: 'blur' }],
      },
      tableData: [],
      // 遮罩层
      total: 0,
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.reset()
        if (this.type == 'edit') {
          const { imgUrl, applySkuList, reason, processingMethod } = this.formData
          Object.keys(this.formData).forEach((key) => {
            this.orderDetail[key] = this.formData[key] ? this.formData[key] : ''
          })
          this.selectTable = applySkuList.map((item) => {
            return {
              ...item,
              handleNum: item.num,
            }
          })
          this.orderSkuTable = JSON.parse(JSON.stringify(this.selectTable))

          this.form.imgList = imgUrl
          this.form.reason = reason
          this.form.wantProcessingMethod = processingMethod
        }
      }
    },
  },
  created() {},
  methods: {
    get_shop_type_list() {
      useDict('shop_type').then(({ shop_type }) => {
        this.shop_type_list = shop_type
      })
    },
    handleShopTypeName(type) {
      const index = this.shop_type_list.findIndex((i) => i.dictValue == type)
      return this.shop_type_list[index]?.dictLabel
    },
    reset() {
      this.tableData = []
      this.orderSkuTable = []
      this.selectTable = []
      Object.keys(this.queryParams).forEach((key) => (this.queryParams[key] = ''))
      Object.keys(this.orderDetail).forEach((key) => (this.orderDetail[key] = ''))
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
    },
    handleSelectionChange(rows) {
      this.tableCheck = rows
      this.selectTable = JSON.parse(JSON.stringify(rows)).map((item) => {
        return {
          ...item,
          maxHandleNum: item.handleNum,
        }
      })
    },
    handleEditApply() {
      const data = {
        id: this.orderDetail.id,
        imgUrl: this.form.imgList,
        reason: this.form.reason,
      }
      updateOrderQuestionApply(data).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })

          this.cancel()
          this.$emit('getList')
        }
      })
    },
    handleApply() {
      if (this.selectTable.length == 0) {
        return this.$message.error(this.$t('请选择问题产品'))
      }
      const data = {
        ...this.orderDetail,
        orderApplySkuList: this.selectTable,
        imgUrl: this.form.imgList,
        reason: this.form.reason,
        wantProcessingMethod: this.form.wantProcessingMethod,
      }
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          insertOrderQuestionApply(data).then((res) => {
            const { code, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })

              this.cancel()
              this.$emit('getList')
            }
          })
        }
      })
    },
    handleOrderNo(row) {
      const _data = {
        orderBatchId: row.orderBatchId,
        orderNo: row.orderNo,
        platformType: row.platformType,
      }
      getOrderApplyInfo(_data).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.orderSkuTable = data.orderApplySkuList
          Object.keys(this.orderDetail).forEach((key) => {
            this.orderDetail[key] = data[key] ? data[key] : ''
          })
        }
      })
    },

    /** 查询供应厂家列表 */
    getList() {
      if (this.queryParams.orderNo == '') return this.$message.error('请输入订单号')
      this.loading = true
      getOrderListByOrderNo(this.queryParams)
        .then((res) => {
          this.tableData = res.data
        })
        .finally(() => (this.loading = false))
    },
    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  padding: 0 10px;
}
.apply-main {
  $boder: 2px solid #d2cdcd;
  display: flex;
  width: 100%;
  border-radius: 8px;
  border: $boder;
  overflow: auto;
  &-left {
    flex: 2;
    border-right: $boder;
    display: flex;
    flex-direction: column;
    &-search {
      padding: 10px;
    }
    &-title {
      padding: 10px;
      border-top: $boder;
      border-bottom: $boder;
      font-weight: bold;
    }
    &_table {
      padding: 1px;
    }
  }
  &-right {
    flex: 5;
    &-head {
    }
    &-list {
      display: flex;
      gap: 5px;
      &_item {
        flex: 1;
        &_title {
          margin: 10px 0;
          font-weight: bold;
        }
      }
    }
  }
}

.template-img {
  display: flex;
  overflow: auto;
  overflow-y: hidden;
  // width: 600px;

  &_item {
    margin: 2px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background-color: #fff;
    border: 1px solid #e1dddd;
    border-radius: 8px;
    padding: 5px;

    img {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 3px;
    }

    .delete-img {
      margin: 5px;

      &:hover {
        color: red;
      }
    }
  }
}
.upload-demo {
  display: flex;
  align-items: center;
  justify-content: center;

  .upload-box {
    width: 60px;
    height: 60px;
    border: 2px dotted #ccc;
    margin: 10px;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #9a9a9a;

      i {
        color: #9a9a9a;
      }
    }

    i {
      font-size: 30px;
      color: #ccc;
    }
  }
}
</style>
